package poketdd.repository;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

import poketdd.bean.Pokemon;

public class JdbcPokemonRepository implements PokemonRepository {

	private SimpleJdbcTemplate jdbcTemplate;

	public JdbcPokemonRepository(DataSource dataSource) {
		this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);
	}

	public void registrarPokemon(Pokemon pokemon) {
		String sql = "insert into pokemon values(?,?,?)";
		jdbcTemplate.update(sql, pokemon.getCodigo(), pokemon.getNombre(),
				pokemon.getTipo());
	}

	public Pokemon buscarPokemon(String codigo) {
		String sql = "select * from pokemon where codigo = ?";
		return jdbcTemplate.getJdbcOperations().queryForObject(sql,
				new PokemonRowMapper(), codigo);
	}
	
	//Row Mapper para Spring
	private class PokemonRowMapper
			implements ParameterizedRowMapper<Pokemon>{
		public Pokemon mapRow(ResultSet rs, int rowNum) throws SQLException {
			return mapPokemon(rs);
		}
	}
	
	// Map convierte registro de BD en Objeto Pokemon
	private Pokemon mapPokemon(ResultSet rs) throws SQLException {
		String codigo = rs.getString("codigo");
		String nombre = rs.getString("nombre");
		String tipo = rs.getString("tipo");  
		
		Pokemon pokemon = new Pokemon();
		pokemon.setCodigo(codigo);
		pokemon.setNombre(nombre);
		pokemon.setTipo(tipo);
		return pokemon;
	}
}
